package com.siwei.apply.service.impl;

import com.siwei.apply.domain.Project;
import com.siwei.apply.domain.Tdgy;
import com.siwei.apply.domain.res.TdgyRes;
import com.siwei.apply.domain.vo.TdgyUpdateVo;
import com.siwei.apply.domain.vo.TdgyVo;
import com.siwei.apply.mapper.ProjectMapper;
import com.siwei.apply.mapper.TdgyMapper;
import com.siwei.apply.service.TdgyService;
import com.siwei.common.core.utils.bean.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.siwei.apply.domain.LandType;
import com.siwei.apply.domain.res.LandTypeTreeRes;
import com.siwei.apply.mapper.LandTypeMapper;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.siwei.apply.common.Common.UserId;

import org.springframework.transaction.annotation.Transactional;
import com.siwei.apply.domain.ProjectWorkflow;
import com.siwei.apply.domain.Workflow;
import com.siwei.apply.mapper.ProjectWorkflowMapper;
import com.siwei.apply.mapper.WorkflowMapper;

/**
 * 土地供应 服务实现类
 */
@Service
public class TdgyImpl implements TdgyService {
    @Autowired
    private TdgyMapper tdgyMapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private LandTypeMapper landTypeMapper;
    // 新增：项目流程相关Mapper
    @Autowired
    private ProjectWorkflowMapper projectWorkflowMapper;
    @Autowired
    private WorkflowMapper workflowMapper;

    @Override
    public Boolean isExit(String projectId) {
        return tdgyMapper.isExit(projectId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String add(TdgyVo tdgyVo) {
        Tdgy tdgy = new Tdgy();
        BeanUtils.copyProperties(tdgyVo, tdgy);
        tdgy.generateId();
        tdgy.setCreatorId(UserId);
        tdgyMapper.add(tdgy);
        // 添加项目流程（仿照YdbpImpl）
        Integer projectType = projectMapper.getProjectTypeById(tdgy.getProjectId());
        Workflow workflow = workflowMapper.selectByProjectTypeAndTableName(projectType, "t_tdgy");
        Workflow workflowPrev = workflowMapper.selectPrevByProjectTypeAndTableName(projectType, "t_tdgy");
        String parentId = "";
        if (workflowPrev != null) {
            List<ProjectWorkflow> projectWorkflows = projectWorkflowMapper.selectByProjectIdAndNodeTableName(tdgy.getProjectId(), workflowPrev.getTableName());
            if (projectWorkflows != null && !projectWorkflows.isEmpty()) {
                parentId = projectWorkflows.get(0).getNodeId();
            }
        }
        ProjectWorkflow projectWorkflow = new ProjectWorkflow();
        projectWorkflow.setId(tdgy.getId());
        projectWorkflow.setParentId(parentId);
        projectWorkflow.setWorkflowId(workflow.getId());
        projectWorkflow.setProjectId(tdgy.getProjectId());
        projectWorkflow.setNodeId(tdgy.getId());
        projectWorkflow.setNodeTableName(workflow.getTableName());
        projectWorkflow.setWorkflowName(workflow.getName());
        projectWorkflowMapper.add(projectWorkflow);
        return tdgy.getId();
    }

    @Override
    public TdgyRes get(String projectId) {
        Tdgy tdgy = tdgyMapper.get(projectId);
        Project project = projectMapper.get(projectId);

        TdgyRes tdgyRes = new TdgyRes();
        if (tdgy != null) {
            BeanUtils.copyProperties(tdgy, tdgyRes);
        }
        tdgyRes.setProjectId(projectId);
        tdgyRes.setProjectName(project.getName());
        tdgyRes.setProjectCode(project.getCode());
        return tdgyRes;
    }

    @Override
    public TdgyRes getById(String id) {
        Tdgy tdgy = tdgyMapper.getById(id);
        if (tdgy == null) {
            return null;
        }
        Project project = projectMapper.get(tdgy.getProjectId());
        TdgyRes tdgyRes = new TdgyRes();
        BeanUtils.copyProperties(tdgy, tdgyRes);
        tdgyRes.setProjectId(tdgy.getProjectId());
        tdgyRes.setProjectName(project.getName());
        tdgyRes.setProjectCode(project.getCode());
        return tdgyRes;
    }

    @Override
    public void update(TdgyUpdateVo tdgyUpdateVo) {
        tdgyMapper.update(tdgyUpdateVo);
    }

    @Override
    public List<LandTypeTreeRes> getLandTypeTree() {
        List<LandType> all = landTypeMapper.selectAll();
        // 转换为节点
        List<LandTypeTreeRes> nodes = all.stream().map(type -> {
            LandTypeTreeRes node = new LandTypeTreeRes();
            node.setCode(type.getCode());
            node.setName(type.getName());
            node.setParentCode(type.getParentCode());
            return node;
        }).collect(Collectors.toList());
        // 构建树
        Map<String, LandTypeTreeRes> nodeMap = nodes.stream().collect(Collectors.toMap(LandTypeTreeRes::getCode, n -> n));
        List<LandTypeTreeRes> roots = nodes.stream().filter(n -> n.getParentCode() == null || n.getParentCode().isEmpty() || !nodeMap.containsKey(n.getParentCode())).collect(Collectors.toList());
        nodes.forEach(n -> {
            if (n.getParentCode() != null && nodeMap.containsKey(n.getParentCode())) {
                nodeMap.get(n.getParentCode()).getChildren().add(n);
            }
        });
        return roots;
    }

    @Override
    public void updateHasOnchain(String id, Boolean hasOnchain) {
        tdgyMapper.updateHasOnchain(id, hasOnchain);
    }
}
